package com.reger.easemob.autoconfig;

import java.io.File;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;

import com.reger.easemob.api.Easemob;
import com.reger.easemob.properties.EasemobProperties;

import okhttp3.Cache;
import okhttp3.CookieJar;
import okhttp3.Interceptor.Chain;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

@Configuration
@EnableConfigurationProperties(EasemobProperties.class)
public class EasemobAutoConfiguration {
	private final String API_URL = "http://a1.easemob.com/";
	
	@Autowired
	private EasemobProperties easemobProperties;
	
	@Bean
	public Easemob easemob(){
		Assert.hasText(easemobProperties.getAppName(), "环信AppName不可以为空");
		Assert.hasText(easemobProperties.getOrgName(), "环信OrgName不可以为空");
		Retrofit retrofit = new Retrofit.Builder().baseUrl(API_URL)
				.addConverterFactory(GsonConverterFactory.create())
				.callbackExecutor(Executors.newScheduledThreadPool(easemobProperties.getCorePoolSize()))
				.validateEagerly(easemobProperties.isValidateEagerly())
				.client(new OkHttpClient.Builder()
						.cache(new Cache(new File("http_cache"), 1024 * 1024 * 100))
						.readTimeout(easemobProperties.getReadTimeout(), TimeUnit.SECONDS)
						.writeTimeout(easemobProperties.getWriteTimeout(), TimeUnit.SECONDS)
						.connectTimeout(easemobProperties.getConnectTimeout(), TimeUnit.SECONDS)
						.cookieJar(CookieJar.NO_COOKIES)
						.addInterceptor((Chain chain)->{
							Request request=chain.request();
							String url=request.url().url().toString();
							url=url
									.replace("%7Borg_name%7D", easemobProperties.getOrgName())
									.replace("%7Bapp_name%7D",  easemobProperties.getAppName());
							return chain.proceed(request.newBuilder().url(url).build());
						})
						.build())
				.build();
		return new Easemob(retrofit);
	}

}
